package com.kgc.pay.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import utils.AlipayConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class AliPayController {

    @RequestMapping("/pay/notify_url")
    public String notify_url(){
        return "notify_url";
    }

    @RequestMapping("/pay/return_url")
    public String return_url(){
        return "return_url";
    }
    /**
     *
     * @param trade_no  用户的订单编号

     * @param total_amount  订单总金额

     * @return
     */
     @RequestMapping("aliPay/pay/{trade_no}/{total_amount}")
     public void createPay(@PathVariable("trade_no") String trade_no, @PathVariable("total_amount")String total_amount,
                           HttpServletRequest request, HttpServletResponse response,
                           ModelMap map) throws Exception{
         //获得初始化的AlipayClient
//获得初始化的AlipayClient
         String subject="订单说明";
         String body="商品说明";

         AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);


         //设置请求参数
         AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
         alipayRequest.setReturnUrl(AlipayConfig.return_url);
         alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

         alipayRequest.setBizContent("{\"out_trade_no\":\""+ trade_no +"\","
                 + "\"total_amount\":\""+ total_amount +"\","
                 + "\"subject\":\""+ subject +"\","
                 + "\"body\":\""+ body +"\","
                 + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

         //请求
         String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();


     }


}
